const router = require('express').Router()
const { chkToken } = require('../../util')
const {query} = require('../../db')
const md5 = require('md5')
const { key, mode } = require('../../config')
const moment = require('moment')
const { do_wxpay } = require('../../pay')
const redis = require('../../redis')

router.get('/', chkToken, async (req, res, next)=>{
    let userInfo = await query('SELECT * FROM users WHERE id=?', req.userId).catch(next)
    if(userInfo === undefined) return

    delete userInfo[0].password

    res.json({
        'ok': 1,
        'data': userInfo[0]
    })
})

router.get('/money', chkToken, async (req, res, next)=>{
    let userInfo = await query('SELECT money FROM users WHERE id=?', req.userId).catch(next)
    if(userInfo === undefined) return

    delete userInfo[0].password

    res.json({
        'ok': 1,
        'data': {
            money: userInfo[0].money
        }
    })
})

router.put('/avatar', chkToken, async (req, res, next)=>{
    let userInfo = await query('UPDATE users SET avatar = ? WHERE id=?', [req.body.avatar, req.userId]).catch(next)
    if(userInfo === undefined) return


    res.json({
        'ok': 1
    })
})

router.post('/money', chkToken, async (req, res, next)=>{

    let money = req.body.money

    if(!/^\d+(\.\d{1,2})?$/.test(money)) {
        res.json({
            'ok': 0,
            'error': '金额是大于0的数字！'
        })
        return
    }

    let order_sn = Date.now().toString() + req.userId + parseInt(Math.random() * 1000)

    let data = {
        addtime: moment().unix(),
        user_id: req.userId,
        money,
        order_sn,
        pay_status: 0
    }
    let sql = 'INSERT INTO orders SET ?'
    let ret = await query(sql, data).catch(next)
    if(ret === undefined) return

    let qrcode = await do_wxpay(order_sn, money, req.ip)

    res.json({
        'ok': 1,
        'data': {
            order_sn,
            qrcode
        }
    })
})

router.post('/', async (req, res, next)=>{
    let mobile = req.body.mobile
    let name = req.body.name
    let password = req.body.password
    let sms_code = req.body.sms_code

    if(mode === 'dev') {
        if(sms_code != 1234) {
            res.json({
                'ok': 0,
                'error': '短信验证码错误！'
            })
            return 
        }
    } else {

        let code = await (()=>{
            return new Promise((resolve, reject)=>{
                redis.get('code_'+mobile, (err, ret)=>{
                    if(err) resolve(null)
                    else resolve(ret)
                })
            })
        })()

        if(sms_code != code) {
            res.json({
                'ok': 0,
                'error': '短信验证码错误！'
            })
            return 
        }
    }
    

    let total = await query('SELECT COUNT(*) total FROM users WHERE mobile=?', mobile).catch(next)
    if(total === undefined) return

    if(total[0].total > 0) {
        res.json({
            'ok': 0,
            'error': '手机号码已经存在！'
        })
        return 
    }

    let data = {
        mobile,
        name,
        money: 0,
        password: md5(password + key)
    }
    let ret = await query('INSERT INTO users SET ?', data).catch(next)
    if(ret === undefined) return

    res.json({
        'ok': 1
    })
})


module.exports = router